<template>
    <div class="page-box">
        <div class="qr-container">
            <div class="qr-box">
                <div id="reader"></div>
            </div>
        </div>
        <div class="btn-box">
            <div>
                <van-icon name="arrow-left" @click="clickBack" />
            </div>
            <div>
                <van-uploader v-model="state.fileList" :preview-image="false" :after-read="uploadImg">
                    <van-icon name="photo-o" />
                </van-uploader>
            </div>
        </div>
    </div>

    <van-toast v-model:show="show" style="padding: 0">
        <template #message>
            <van-image :src="image" width="200" height="140" style="display: block" />
        </template>
    </van-toast>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { Html5Qrcode } from "html5-qrcode";
import { showToast, Toast } from "vant";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {getReservationOne} from "@/api/reservation.js";
const router = useRouter();
const state = reactive({
    html5QrCode: null,
    fileList: [],
});

const show = ref(false); // 添加 show 的定义
const image = ref(''); // 添加 image 的定义

onMounted(() => {
    getCamerasInfo();
});

onUnmounted(() => {
    if (state.html5QrCode?.isScanning) {
        stopScan();
    }
});

const clickBack = () => {
  console.log(12312312)
  router.replace({ name: "Home" });
};

const getCamerasInfo = () => {
    Html5Qrcode.getCameras()
        .then((devices) => {
            if (devices && devices.length) {
                state.html5QrCode = new Html5Qrcode("reader");
                startScan();
            }
        })
        .catch((err) => {
            showToast({ message: "摄像头无访问权限！", duration: 2000 });
        });
};
const startScan =  () => {
    state.html5QrCode
        .start(
            { facingMode: "environment" },
            { fps: 1, qrbox: { width: 250, height: 250 } },
            (decodedText, decodedResult) => {
              if (decodedText !=null){
                getReservationOne().then(res=>{
                  if (res.data.code ==200){
                    ElMessage.success("使用成功")
                    router.push("/useReservation")
                  }else {
                    ElMessage.error("请先预约")
                    router.push("/home")
                  }
                })

              }


              stopScan()
            }
        )
        .catch((err) => {
            console.log("扫码失败", err);
        });
};

const stopScan = () => {
    state.html5QrCode
        .stop()
        .then(() => console.log("已停止扫码"))
        .catch((err) => {
            console.log(err);
            showToast("停止失败");
        });
};

const uploadImg = () => {
    try {
        window.qrcode.callback = (result) => {
            showToast(result);
        };
        let file = state.fileList[0]?.file;
        if (!file) throw new Error("No file selected.");

        let reader = new FileReader();
        reader.onload = (e) => {
            window.qrcode.decode(e.target.result);
        };
        reader.readAsDataURL(file);
    } catch (error) {
        showToast({ message: "识别失败！", duration: 2000 });
    }
};
</script>

<style scoped>
.page-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #000;
}

.qr-container {
    position: relative;
    /*width: 100%;*/
    /*height: 26%;*/
    top:240px;
}

.qr-box {
    height: 100%;
}

/*#reader {*/
/*    position: absolute;*/
/*    top: 50%;*/
/*    left: 50%;*/
/*    transform: translate(-50%, 60%);*/
/*}*/

.btn-box {
    flex: 1;
    display: flex;
    justify-content: space-around;
    /*align-items: flex-start;*/
    /*padding: 12px;*/
    color: #fff;
    font-size: 28px;
    margin-top: 480px;
}
</style>
